<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018-06-21
 * Time: 10:45
 */
namespace app\api\common;
use think\Controller;
use think\Db;
use think\Exception;

class Collection extends Controller
{
    protected static $err_code = 0;

    /**
     *
     * @apiGroup Collection
     * @apiVersion 2.0.0
     * @apiDescription 收藏列表
     * @api {post} /collection.index 收藏列表
     * @apiName Collection_index
     * @apiParam {int} member_id 用户id
     * @apiParam {String} token
     * @apiParam {String} sign
     * @apiParam {int} page 页码（data外）
     *
     * @apiSuccess {int} code 结果码
     * @apiSuccess {String} msg 消息说明
     * @apiSuccess {Object} data
     * @apiSuccess {int} data.total 总条数
     * @apiSuccess {String} data.per_page 每页条数
     * @apiSuccess {String} data.current_page 当前页码
     * @apiSuccess {String} data.last_page 下一页页码
     * @apiSuccess {Object} data.data
     * @apiSuccess {int} data.data.itemid 淘宝id
     * @apiSuccess {String} data.data.itemtitle 标题
     * @apiSuccess {String} data.data.itemprice 在售价
     * @apiSuccess {String} data.data.itemendprice  券后价
     * @apiSuccess {String} data.data.itempic 	封面图链接
     * @apiSuccess {String} data.data.couponurl 优惠券链接
     * @apiSuccess {String} data.data.shoptype 天猫/淘宝类型：天猫（B） 普通淘宝店铺（C）
     * @apiSuccess {float} data.data.itemsale 月销量
     * @apiSuccess {float} data.data.couponmoney 优惠券金额
     * @apiSuccess {int} data.data.couponstarttime 优惠券开始时间
     * @apiSuccess {int} data.data.couponendtime 优惠券结束时间
     * @apiSuccess {int} data.data.is_haohuo 是否为好货
     * @apiSuccess {int} data.data.share_url 分享链接
     * @apiSuccess {Object} data.data.itempic_list 图片列表
     * @apiSuccessExample 成功示例
     *  HTTP/1.1 200 OK
     *  {
     *     code:200,
     *     msg:'success',
     *     data:{
     *         next_page:''
     *          data:{
    ...
     *              }
     *	   }
     *  }
     *
     *  @apiError code 0 系统异常错误
     *  @apiError msg token已经过期
     *  @apiErrorExample {json} 失败示例
     *  HTTP/1.1 404 Not Found
     *  {
     *     code:0,
     *      msg:'失败或没有数据返回',
     *   }
     */
    public static function index($param){
        if (!isset($param['member_id']) || empty($param['member_id'])){
            return ['data' => '', 'code' => 400001, 'msg' => '参数错误，用户id未传'];
        }
        try{
            $data_list = Db::table('yf_collection')
                ->field('collection_id,itemid,itemtitle,itemprice,itemendprice,itempic,couponurl,shoptype,itemsale,couponmoney,couponstarttime,couponendtime,is_haohuo')
                ->where(['member_id'=>['eq',$param['member_id']],'status'=>1])
                ->order(['add_time'=>'desc'])->paginate(10);
            $data_list = $data_list->toArray();
            if (!empty($data_list['data'])){
                foreach ($data_list['data'] as $k=>$v){
                    $small_pic = explode(',',$v['itempic']);
                    foreach ($small_pic as $key=>$val){
                        if ($key==0){
                            $data_list['data'][$k]['itempic'] = get_img_url($val);
                        }
                        $small_pic[$key] = get_img_url($val);
                    }
                    $data_list['data'][$k]['itempic_list'] = $small_pic;
                    $data_list['data'][$k]['share_url'] = '';
                }
            }
            return ['code'=>200,'msg'=>'SUCCESS','data'=>$data_list];
        }catch (Exception $e){
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }
    }

    /**
     *
     * @apiGroup Collection
     * @apiVersion 2.0.0
     * @apiDescription 添加收藏
     * @api {post} /collection.add_collection 添加收藏
     * @apiName Collection_add_collection
     * @apiParam {int} member_id 用户id
     * @apiParam {int} itemid 淘宝商品id
     * @apiParam {int} is_haohuo 是否是好货商品 0不是 1是
     * @apiParam {int} json
     * @apiParam {String} json.itemtitle 标题
     * @apiParam {String} json.itemdesc 描述 空
     * @apiParam {String} json.itemprice 在售价
     * @apiParam {int} json.itemsale 销量
     * @apiParam {String} json.itempic 图片
     * @apiParam {String} json.itemendprice 券后价
     * @apiParam {String} json.shoptype 店铺类型：天猫（B）C店（C）
     * @apiParam {String} json.couponurl 优惠券链接
     * @apiParam {String} json.couponmoney 优惠券金额
     * @apiParam {int} json.couponstarttime 优惠券开始时间
     * @apiParam {int} json.couponendtime 优惠券结束时间
     * @apiParam {String} token
     * @apiParam {String} sign
     *
     * @apiSuccess {int} code 结果码
     * @apiSuccess {String} msg 消息说明
     * @apiSuccessExample 成功示例
     *  HTTP/1.1 200 OK
     *  {
     *     code:200,
     *     msg:'success',
     *     data:{
     *         next_page:''
     *          data:{
    ...
     *              }
     *	   }
     *  }
     *
     *  @apiError code 0 系统异常错误
     *  @apiError msg token已经过期
     *  @apiErrorExample {json} 失败示例
     *  HTTP/1.1 404 Not Found
     *  {
     *     code:0,
     *      msg:'失败或没有数据返回',
     *   }
     */
    public static function add_collection($param){
        if (!isset($param['member_id']) || empty($param['member_id']) || !isset($param['itemid']) || empty($param['itemid'])){
            return ['data' => '', 'code' => 400001, 'msg' => '参数错误，用户id未传'];
        }
        Db::startTrans();//开启事务
        try{
            if (isset($param['json']) && !empty($param['json'])){
                $goods_info = json_decode($param['json'],true);
                $data['itemtitle'] = $goods_info['itemtitle'];
                $data['itemprice'] = $goods_info['itemprice'];
                $data['itemid'] = $goods_info['itemid'];
                $data['itemdesc'] = '';
                $data['couponstarttime'] = $goods_info['couponstarttime'];
                $data['couponendtime'] = $goods_info['couponendtime'];
                $data['shoptype'] = $goods_info['shoptype'];
                $data['couponurl'] = $goods_info['couponurl'];
                $data['couponmoney'] = $goods_info['couponmoney'];
                $data['itempic'] = $goods_info['itempic'];
                $data['itemendprice'] = $goods_info['itemendprice'];
                $data['itemsale'] = $goods_info['itemsale'];
                $data['add_time'] = time();
                $data['is_haohuo'] = $param['is_haohuo'];
                $data['member_id'] = $param['member_id'];
                if (Db::table('yf_collection')->insert($data)) {
                    Db::commit();
                    return ['code' => 200, 'msg' => 'success'];
                } else {
                    self::$err_code = 400032;
                    throw new Exception('收藏失败');
                }
            }else {
                if ($param['is_haohuo'] == 1) {
                    $datainfo = Db::name('colection')->where(['itemid' => $param['itemid'], 'is_haohuo' => 1, 'member_id' => $param['member_id']])->find();
                    if (!empty($datainfo) && $datainfo['status'] == 1) {
                        self::$err_code = 400032;
                        throw new Exception('该商品已添加过了，请勿重复添加');
                    }else{
                        $info = Db::name('good')
                            ->field('title,price,itemid,desc,begin_time,end_time,shoptype,coupon_url,coupon_price,itempic,itemendprice,sell_counter')
                            ->where('itemid', $param['itemid'])->find();
                        if (!empty($info)){
                            $data['itemtitle'] = $info['title'];
                            $data['itemprice'] = $info['price'];
                            $data['itemid'] = $info['itemid'];
                            $data['itemdesc'] = $info['desc'];
                            $data['couponstarttime'] = $info['begin_time'];
                            $data['couponendtime'] = $info['end_time'];
                            $data['shoptype'] = $info['shoptype'];
                            $data['couponurl'] = $info['coupon_url'];
                            $data['couponmoney'] = $info['coupon_price'];
                            $data['itempic'] = $info['itempic'];
                            $data['itemendprice'] = $info['itemendprice'];
                            $data['itemsale'] = $info['sell_counter'];
                            $data['add_time'] = time();
                            $data['is_haohuo'] = $param['is_haohuo'];
                            $data['member_id'] = $param['member_id'];
                            if (Db::table('yf_collection')->insert($data)) {
                                Db::commit();
                                return ['code' => 200, 'msg' => 'success'];
                            } else {
                                self::$err_code = 400032;
                                throw new Exception('收藏失败');
                            }
                        }else{
                            if (Db::table('yf_collection')->where(['collection_id' => $datainfo['collection_id']])->setField('status', 1)) {
                                Db::commit();
                                return ['code' => 200, 'msg' => 'success'];
                            } else {
                                self::$err_code = 400032;
                                throw new Exception('收藏失败');
                            }
                        }
                    }
                } else {
                    $datainfo = Db::name('collection')->where(['itemid' => $param['itemid'], 'is_haohuo' => 0, 'member_id' => $param['member_id']])->find();
                    if (!empty($datainfo) && $datainfo['status'] == 1) {
                        self::$err_code = 400032;
                        throw new Exception('该商品已添加过了，请勿重复添加');
                    }
                    if (!empty($datainfo) && $datainfo['status'] == 0) {
                        $info = self::get_data($param['itemid']);
                        if ($info['code'] == 200 && !empty($info['data'])) {
                            $info['data']['add_time'] = time();
                            $info['data']['is_haohuo'] = $param['is_haohuo'];
                            $info['data']['member_id'] = $param['member_id'];
                            $info['data']['status'] = 1;
                            if (Db::table('yf_collection')->where(['collection_id' => $datainfo['collection_id']])->update($info['data'])) {
                                Db::commit();
                                return ['code' => 200, 'msg' => 'success'];
                            } else {
                                self::$err_code = 400032;
                                throw new Exception('收藏失败');
                            }
                        } else {
                            if (Db::table('yf_collection')->where(['collection_id' => $datainfo['collection_id']])->setField('status', 1)) {
                                Db::commit();
                                return ['code' => 200, 'msg' => 'success'];
                            } else {
                                self::$err_code = 400032;
                                throw new Exception('收藏失败');
                            }
                        }
                    } else {
                        $info = self::get_data($param['itemid']);
                        if ($info['code'] == 200 && !empty($info['data'])) {
                            $info['data']['add_time'] = time();
                            $info['data']['is_haohuo'] = $param['is_haohuo'];
                            $info['data']['member_id'] = $param['member_id'];
                            $info['data']['status'] = 1;
                            if (Db::table('yf_collection')->insert($info['data'])) {
                                Db::commit();
                                return ['code' => 200, 'msg' => 'success'];
                            } else {
                                self::$err_code = 400032;
                                throw new Exception('收藏失败');
                            }
                        } else {
                            self::$err_code = 400032;
                            throw new Exception('收藏失败,无该商品的相关信息');
                        }
                    }
                }
            }
//                    if (!empty($datainfo) && $datainfo['status'] == 0){
//                        $data = Db::name('items')
//                            ->field('itemid,itemtitle,itemprice,itemendprice,itempic,itemdesc,couponurl,shoptype,itemsale,couponmoney,couponstarttime,couponendtime')
//                            ->where('itemid',$param['itemid'])->find();
//                        if (!empty($data)){
//                            $data['add_time'] = time();
//                            $data['is_haohuo'] = $param['is_haohuo'];
//                            $data['member_id'] = $param['member_id'];
//                            $data['status'] = 1;
//                            if (!Db::table('yf_collection')->where(['collection_id'=>$datainfo['collection_id']])->update($data)){
//                                throw new Exception('收藏失败');
//                            }
//                        }else{
//                            $recommend_data = Db::name('recommend')->field('itemid,itemtitle,itemprice,itemendprice,itempic,couponurl,shoptype,itemsale,couponmoney,couponstarttime,couponendtime')
//                                ->where('itemid',$param['itemid'])->find();
//                            if (!empty($recommend_data)){
//                                $data['add_time'] = time();
//                                $data['is_haohuo'] = $param['is_haohuo'];
//                                $data['member_id'] = $param['member_id'];
//                                $data['status'] = 1;
//                                if (!Db::table('yf_collection')->where(['collection_id'=>$datainfo['collection_id']])->update($data)){
//                                    throw new Exception('收藏失败');
//                                }
//                        }
//                    }
//
//
//                    $data = Db::name('items')
//                        ->field('itemid,itemtitle,itemprice,itemendprice,itempic,itemdesc,couponurl,shoptype,itemsale,couponmoney,couponstarttime,couponendtime')
//                        ->where('itemid',$param['itemid'])->find();
//                    if (empty($data)){
//                        $data = Db::name('recommend')->field('itemid,itemtitle,itemprice,itemendprice,itempic,couponurl,shoptype,itemsale,couponmoney,couponstarttime,couponendtime')
//                            ->where('itemid',$param['itemid'])->find();
//                        if (empty($data)){
//                            $data = Db::name('subject_items')->field('itemid,itemtitle,itemprice,itemendprice,itempic,couponurl,shoptype,itemsale,couponmoney,couponstarttime,couponendtime')
//                                ->where('itemid',$param['itemid'])->find();
//                        }
//                    }
//                }
//            }
//            if (empty($data)){
//                throw new Exception('无该商品的相关信息');
//            }
//            $data['add_time'] = time();
//            $data['is_haohuo'] = $param['is_haohuo'];
//            $data['member_id'] = $param['member_id'];
//            if (Db::table('yf_collection')->insert($data)){
//                Db::commit();
//                return ['code'=>200,'msg'=>'success'];
//            }else{
//                self::$err_code =400032;
//                throw new Exception('商品收藏失败');
//            }
        }catch (Exception $e){
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }
    }

    /**
     *
     * @apiGroup Collection
     * @apiVersion 2.0.0
     * @apiDescription 删除收藏商品
     * @api {post} /collection.del_collection 删除收藏商品
     * @apiName Collection_del_collection
     * @apiParam {int} member_id 用户id
     * @apiParam {int} itemid 淘宝商品id (在详情页中删除需传)
     * @apiParam {int} is_haohuo 是否是好货商品 0不是 1是 (在详情页中删除需传)
     * @apiParam {String} collection_ids 批量删除时的collection_id  如'1,3,5,12,3,5' （这个用于在收藏列表中删除使用）
     * @apiParam {String} token
     * @apiParam {String} sign
     *
     * @apiSuccess {int} code 结果码
     * @apiSuccess {String} msg 消息说明
     * @apiSuccessExample 成功示例
     *  HTTP/1.1 200 OK
     *  {
     *     code:200,
     *     msg:'success',
     *     data:{
     *         next_page:''
     *          data:{
    ...
     *              }
     *	   }
     *  }
     *
     *  @apiError code 0 系统异常错误
     *  @apiError msg token已经过期
     *  @apiErrorExample {json} 失败示例
     *  HTTP/1.1 404 Not Found
     *  {
     *     code:0,
     *      msg:'失败或没有数据返回',
     *   }
     */
    public static function del_collection($param){
        if (!isset($param['member_id']) || empty($param['member_id']) ){
            return ['data' => '', 'code' => 400001, 'msg' => '参数错误，用户id未传'];
        }
        if (!isset($param['collection_ids']) && (!isset($param['itemid'])||empty($param['itemid']) || !isset($param['is_haohuo']))){
            return ['data' => '', 'code' => 400001, 'msg' => '参数错误'];
        }
        if (!isset($param['itemid']) && (!isset($param['collection_ids'])||empty($param['collection_ids']))){
            return ['data' => '', 'code' => 400001, 'msg' => '参数错误'];
        }
        Db::startTrans();//开启事务
        try{
            if (isset($param['collection_ids'])){
                if (Db::table('yf_collection')->where(['collection_id'=>['in',$param['collection_ids']],'member_id'=>$param['member_id']])->setField('status',0)){
                    Db::commit();
                    return ['code' => 200, 'msg' => 'success'];
                }else{
                    self::$err_code = 400033;
                    throw new Exception('删除失败');
                }
            }else{
                if (Db::table('yf_collection')->where(['itemid'=>['eq',$param['itemid']],'is_haohuo'=>$param['is_haohuo'],'member_id'=>$param['member_id']])->setField('status',0)){
                    Db::commit();
                    return ['code' => 200, 'msg' => 'success'];
                }else{
                    self::$err_code = 400033;
                    throw new Exception('删除失败');
                }
            }
        }catch (Exception $e){
            Db::rollback();
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }
    }

    /**
     *
     * @apiGroup Collection
     * @apiVersion 1.0.1
     * @apiDescription 是否是已收藏
     * @api {post} /collection.is_collection 是否是已收藏
     * @apiName Collection_is_collection
     * @apiParam {int} member_id 用户id
     * @apiParam {int} itemid 淘宝商品id (在详情页中删除需传)
     * @apiParam {int} is_haohuo 是否是好货商品 0不是 1是 (在详情页中删除需传)
     * @apiParam {String} token
     * @apiParam {String} sign
     *
     * @apiSuccess {int} code 结果码
     * @apiSuccess {String} msg 消息说明
     * @apiSuccess {int} data 是否已收藏 0未收藏 1已收藏
     * @apiSuccessExample 成功示例
     *  HTTP/1.1 200 OK
     *  {
     *     code:200,
     *     msg:'success',
     *     data:1
     *  }
     *
     *  @apiError code 0 系统异常错误
     *  @apiError msg token已经过期
     *  @apiErrorExample {json} 失败示例
     *  HTTP/1.1 404 Not Found
     *  {
     *     code:0,
     *      msg:'失败或没有数据返回',
     *   }
     */
    public static function is_collection($param){
        if (!isset($param['member_id']) || empty($param['member_id']) ){
            return ['data' => '', 'code' => 400001, 'msg' => '参数错误，用户id未传'];
        }
        if ((!isset($param['itemid'])||empty($param['itemid']) || !isset($param['is_haohuo']) )){
            return ['data' => '', 'code' => 400001, 'msg' => '参数错误'];
        }
        try{
            $num = Db::name('collection')->where(['itemid'=>$param['itemid'],'member_id'=>$param['member_id'],'is_haohuo'=>$param['is_haohuo'],'status'=>1])->count();
            if ($num >0){
                return ['code' => 200, 'msg' => 'success','data'=>1];
            }else{
                return ['code' => 200, 'msg' => 'success','data'=>0];
            }
        }catch (Exception $e){
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }
    }


    /**
     * 根据商品id获取商品信息
     */
    public static function get_data($itemid){
        $data = Db::name('items')
            ->field('itemid,itemtitle,itemprice,itemendprice,itempic,itemdesc,couponurl,shoptype,itemsale,couponmoney,couponstarttime,couponendtime')
            ->where('itemid',$itemid)->find();
        if (empty($data)){
            $recommenddata = Db::name('recommend')->field('itemid,itemtitle,itemprice,itemendprice,itempic,couponurl,shoptype,itemsale,couponmoney,couponstarttime,couponendtime')
                ->where('itemid',$itemid)->find();
            if (empty($recommenddata)){
                $subjectdata = Db::name('subject_items')->field('itemid,itemtitle,itemprice,itemendprice,itempic,couponurl,shoptype,itemsale,couponmoney,couponstarttime,couponendtime')
                    ->where('itemid',$itemid)->find();
                if (empty($subjectdata)){
                    return ['code'=>200,'msg'=>'success','data'=>[]];
                }else{
                    return ['code'=>200,'msg'=>'success','data'=>$subjectdata];
                }
            }else{
                return ['code'=>200,'msg'=>'success','data'=>$recommenddata];
            }
        }else{
            return ['code'=>200,'msg'=>'success','data'=>$data];
        }
    }

}